package common;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import annotation.Aspect;

public class AOPHelper
{

    static
    {

        try
        {
            List<Class<?>> aspectClassList = ClassHelper
                            .getClassListBySuper(BaseAspect.class);
            for (Class<?> aspectClass : aspectClassList)
            {
                if (aspectClass.isAnnotationPresent(Aspect.class))
                {
                    Aspect aspect = aspectClass.getAnnotation(Aspect.class);
                    String pkg = aspect.pkg();
                    String cls = aspect.cls();
                    List<Class<?>> targetClassList = new ArrayList<Class<?>>();
                    if (StringUtils.isNotEmpty(pkg)
                                    && StringUtils.isNotEmpty(cls))
                    {
                        targetClassList.add(Class.forName(pkg + "." + cls));
                    }
                    else
                    {
                        targetClassList.addAll(ClassHelper
                                        .getClassListByPackage(pkg));
                    }
                    if (CollectionUtils.isNotEmpty(targetClassList))
                    {
                        BaseAspect baseAspect = (BaseAspect) aspectClass
                                        .newInstance();
                        for (Class<?> targetClass : targetClassList)
                        {
                            Object targetInstance = BeanHelper
                                            .getBean(targetClass);
                            Object proxyInstance = baseAspect
                                            .getProxy(targetClass);
                            PropertyUtils.copyProperties(proxyInstance,
                                targetInstance);
                            BeanHelper.getBeanMap().put(targetClass,
                                proxyInstance);
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }
}
